package com.chaoxi.picturebackend.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaoxi.picturebackend.annotation.AuthCheck;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageCreateRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.Texttoimage.TextToImageResponse;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.AliYunAiApi;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.CreateOutPaintingTaskResponse;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.CreatePictureOutPaintingTaskRequest;
import com.chaoxi.picturebackend.api.aliyunai.model.expand.GetOutPaintingTaskResponse;
import com.chaoxi.picturebackend.api.imagesearch.ImageSearchApiFacade;
import com.chaoxi.picturebackend.api.imagesearch.model.ImageSearchResult;
import com.chaoxi.picturebackend.common.BaseResponse;
import com.chaoxi.picturebackend.common.DeleteBatchRequest;
import com.chaoxi.picturebackend.common.DeleteRequest;
import com.chaoxi.picturebackend.common.ResultUtils;
import com.chaoxi.picturebackend.constant.UserConstant;
import com.chaoxi.picturebackend.exception.BusinessException;
import com.chaoxi.picturebackend.exception.ErrorCode;
import com.chaoxi.picturebackend.exception.ThrowUtils;
import com.chaoxi.picturebackend.manager.OSSManager;
import com.chaoxi.picturebackend.model.dto.picture.*;
import com.chaoxi.picturebackend.model.entity.Picture;
import com.chaoxi.picturebackend.model.entity.Space;
import com.chaoxi.picturebackend.model.entity.User;
import com.chaoxi.picturebackend.model.enums.PictureReviewStatusEnum;
import com.chaoxi.picturebackend.model.vo.PictureVO;
import com.chaoxi.picturebackend.service.PictureService;
import com.chaoxi.picturebackend.service.SpaceService;
import com.chaoxi.picturebackend.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {
    @Resource
    private PictureService pictureService;
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private OSSManager ossManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private AliYunAiApi aliYunAiApi;

    // 本地缓存
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();

    /**
     * 清除本地缓存
     */
    public void clearLocalCache() {
        LOCAL_CACHE.invalidateAll();
    }

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @ApiOperation("本地上传图片")
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @ApiOperation("url上传图片")
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量上传图片
     * @param pictureUploadByBatchRequest 图片上传参数
     * @param request 请求
     * @return 批量上传图片数量
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量抓取图片")
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 创建 AI 扩图任务
     * @param createPictureOutPaintingTaskRequest 创建任务参数
     * @param request 请求
     * @return 创建任务结果
     */
    @PostMapping("/out_painting/create_task")
    @ApiOperation("创建 AI 扩图任务")
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     * @param taskId 任务id
     * @return 任务结果
     */
    @GetMapping("/out_painting/get_task")
    @ApiOperation("查询 AI 扩图任务")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }

    /**
     * 头像上传
     * @param file
     * @return
     */
    @PostMapping("/upload/avatar")
    @ApiOperation("头像上传")
    public BaseResponse<String> upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        String url = null;
        try {
            User loginUser = userService.getLoginUser(request);
            Long loginUserId = loginUser.getId();
            url = ossManager.upload(file.getBytes(), String.format("public/%s/avatar/%s", loginUserId, file.getOriginalFilename()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResultUtils.success(url);
    }

    /**
     * 下载图片
     */
    @PostMapping("/download")
    @ApiOperation("下载图片")
    public BaseResponse<String> downloadPicture(@RequestBody PictureDownloadRequest downloadRequest) {
        String pictureId = downloadRequest.getId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(pictureService.downloadPicture(pictureId));
    }

    /**
     * 删除图片
     */
    @PostMapping("/delete")
    @ApiOperation("删除图片")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        pictureService.deletePicture(id, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量删除图片
     */
    @PostMapping("/delete/batch")
    @ApiOperation("批量删除图片")
    public BaseResponse<Boolean> deletePicturesBatch(@RequestBody DeleteBatchRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null || deleteRequest.getId().isEmpty(),
                ErrorCode.PARAMS_ERROR, "请选择要删除的图片");

        User loginUser = userService.getLoginUser(request);
        List<Long> ids = deleteRequest.getId();

        // 检查所有图片是否存在且用户有权限删除
        for (Long id : ids) {
            Picture oldPicture = pictureService.getById(id);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员可删除
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "您无权限删除图片 ID: " + id);
            }
        }
        // 执行批量删除
        boolean result = pictureService.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        // 删除对象存储
        for(Long id : ids){
            Picture oldPicture = pictureService.getById(id);
            pictureService.clearPictureFile(oldPicture);
        }
        return ResultUtils.success(true);
    }

    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @ApiOperation("编辑图片（给用户使用）")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量编辑图片
     */
    @PostMapping("/edit/batch")
    @ApiOperation("批量编辑图片")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新图片（仅管理员可用）")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 补充审核参数
//        User loginUser = userService.getLoginUser(request);
//        pictureService.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("根据 id 获取图片（仅管理员可用）")
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @GetMapping("/get/vo")
    @ApiOperation("根据 id 获取图片（封装类）")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
//        log.info("getPictureVOById:{}",id);
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            User loginUser = userService.getLoginUser(request);
            pictureService.checkPictureAuth(loginUser, picture);
        }
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVO(picture, request));
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取图片列表（仅管理员可用）")
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页获取图片列表（封装类）")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片列表（封装类）---- 用多级缓存
     * @param pictureQueryRequest 查询条件
     * @param request 请求
     * @return BaseResponse<Page<PictureVO>>
     */
    @PostMapping("/list/page/vo/cache")
    @ApiOperation("分页获取图片列表（封装类）-- 多级缓存")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                              HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }
        // 查询数据库之前查询缓存
        // 构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        // 查询条件进行哈希
        String hashKey = DigestUtil.md5Hex(queryCondition.getBytes());
        // 构建key：前缀+哈希key
        String cacheKey = String.format("picture:lisVOPage:%s", hashKey);
        // 查询本地缓存
        String cacheValue = LOCAL_CACHE.getIfPresent(cacheKey);
        // 本地缓存命中，直接返回缓存数据
        if (StringUtils.isNotBlank(cacheValue)){
            Page<PictureVO> cachedPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 本地缓存未命中，查询redis缓存
        cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);
        // 缓存命中，存入本地缓存，并返回
        if (StringUtils.isNotBlank(cacheValue)){
            LOCAL_CACHE.put(cacheKey, cacheValue);
            Page<PictureVO> cachedPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 缓存未命中，写入缓存
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装page
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 更新缓存
        cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 更新本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 更新 Redis 缓存，设置过期时间为 5 分钟
        stringRedisTemplate.opsForValue().set(cacheKey, cacheValue, 5, TimeUnit.MINUTES);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片列表（封装类）---- redis缓存
     * @param pictureQueryRequest 查询条件
     * @param request 请求
     * @return BaseResponse<Page<PictureVO>>
     */
    @PostMapping("/list/page/vo/cache_redis")
    @ApiOperation("分页获取图片列表（封装类）-- redis缓存")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithRedisCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }

        // 查询数据库之前查询缓存
        // 构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        // 查询条件进行哈希
        String hashKey = DigestUtil.md5Hex(queryCondition.getBytes());
        // 构建key：前缀+哈希key
        String redisKey = String.format("picture:lisVOPage:%s", hashKey);
        // 查询缓存
        String cacheValue = stringRedisTemplate.opsForValue().get(redisKey);
        // 缓存命中，返回缓存数据
        if (StringUtils.isNotBlank(cacheValue)){
            Page<PictureVO> cachedPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 缓存未命中，写入缓存
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装page
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        String cachedValue = JSONUtil.toJsonStr(pictureVOPage);
        // 设置缓存时间 5-10分钟，防止缓存雪崩问题
        int expireTime = RandomUtil.randomInt(5, 10);
        stringRedisTemplate.opsForValue().set(redisKey, cachedValue, expireTime, TimeUnit.MINUTES);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片列表（封装类）---- 用本地缓存
     * @param pictureQueryRequest 查询条件
     * @param request 请求
     * @return BaseResponse<Page<PictureVO>>
     */
    @PostMapping("/list/page/vo/cache_caffeine")
    @ApiOperation("分页获取图片列表（封装类）-- 本地缓存")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCaffeineCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }

        // 查询数据库之前查询缓存
        // 构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        // 查询条件进行哈希
        String hashKey = DigestUtil.md5Hex(queryCondition.getBytes());
        // 构建key：前缀+哈希key
        String caffeineKey = String.format("lisVOPage:%s", hashKey);
        // 查询缓存
        String cacheValue = LOCAL_CACHE.getIfPresent(caffeineKey);
        // 缓存命中，返回缓存数据
        if (StringUtils.isNotBlank(cacheValue)){
            Page<PictureVO> cachedPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 缓存未命中，写入缓存
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装page
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入本地缓存
        String cachedValue = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(caffeineKey, cachedValue);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 审核图片
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("图片审核")
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取待审核图片列表
     */
    @PostMapping("/list/page/pending")
    @ApiOperation("分页获取待审核图片列表")
    public BaseResponse<Page<PictureVO>> listPendingPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                    HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 30, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        // 设置查询条件为待审核状态
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        pictureQueryRequest.setUserId(loginUser.getId());
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 刷新图片缓存
     * @return 是否刷新成功
     */
    @PostMapping("/picture/refreshCache")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("刷新图片缓存（仅管理员）")
    public BaseResponse<Boolean> refreshPictureCache() {
        try {
            // 清除所有以"picture:"为前缀的Redis缓存
            stringRedisTemplate.delete(stringRedisTemplate.keys("picture:*"));
            // 清除本地缓存
            clearLocalCache();
            return ResultUtils.success(true);
        } catch (Exception e) {
            log.error("刷新图片缓存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "刷新缓存失败");
        }
    }

    /**
     * 以图搜图
     * 通过上传的图片在数据库中查找相似图片
     * 
     * @param searchPictureByPictureRequest 包含待搜索图片ID的请求对象
     * @return BaseResponse<List<ImageSearchResult>> 图片搜索结果列表
     */
    @PostMapping("/search/picture")
    @ApiOperation("以图搜图")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        // 参数校验
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        
        // 获取图片信息
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 调用图片搜索引擎进行搜索
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getOriginUrl());
        return ResultUtils.success(resultList);
    }

    /**
     * 根据图片主色调搜索图片
     * 
     * @param searchPictureByColorRequest 搜索请求参数，包含主色调和空间ID
     * @param request HTTP请求对象，用于获取当前登录用户
     * @return 符合条件的图片列表，按与目标颜色的相似度排序
     */
    @PostMapping("/search/color")
    @ApiOperation("根据图片主色调搜索图片")
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }
    
    /**
     * 批量更新图片主色调
     * @param request 请求
     * @return 更新结果
     */
    @PostMapping("/update/color/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("批量更新图片主色调")
    public BaseResponse<Integer> updatePicturesColorBatch(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        int updateCount = pictureService.batchUpdatePicturesColor();
        return ResultUtils.success(updateCount);
    }

    /**
     * 创建文字生成图片任务
     * @param textToImageCreateRequest 文字生成图片请求参数
     * @param request 请求
     * @return 创建任务结果
     */
    @PostMapping("/text_to_image/create_task")
    @ApiOperation("创建文字生成图片任务")
    public BaseResponse<TextToImageResponse> createTextToImageTask(
            @RequestBody TextToImageCreateRequest textToImageCreateRequest,
            HttpServletRequest request) {
        if (textToImageCreateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        TextToImageResponse response = pictureService.createTextToImageTask(textToImageCreateRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询文字生成图片任务状态
     * @param taskId 任务ID
     * @param request 请求
     * @return 任务结果
     */
    @GetMapping("/text_to_image/get_task")
    @ApiOperation("查询文字生成图片任务状态")
    public BaseResponse<TextToImageResponse> getTextToImageTask(String taskId, HttpServletRequest request) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        TextToImageResponse response = pictureService.getTextToImageTask(taskId, loginUser);
        return ResultUtils.success(response);
    }
}
